package com.twan.kotlinbase.ui

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.jaeger.library.StatusBarUtil
import com.tencent.qcloud.tim.demo.login.UserInfo
import com.tencent.qcloud.tim.demo.utils.DemoLog
import com.tencent.qcloud.tim.uikit.TUIKit
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack
import com.tencent.qcloud.tim.uikit.utils.ToastUtil
import com.twan.kotlinbase.R
import com.twan.kotlinbase.network.RxHttpScope
import com.twan.kotlinbase.util.MyUtils
import com.twan.kotlinbase.widgets.router.Router
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse


class FirstActivity : AppCompatActivity(){

    private val DELAY_TIME = 1L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setColor(this, resources.getColor(R.color.white), 0)
        setContentView(R.layout.activity_first)


        if(MyUtils.getUserid().isNullOrEmpty()){
            goMain();
        }else{
            loginIM();
        }


//        if(SPUtils.getInstance().getBoolean("iseverused")){
//            Router.newIntent(this@FirstActivity).to(MainActivity::class.java).launch()
//            finish()
//        } else {
//        }
    }

    private fun loginIM() {
        RxHttpScope().launch {
            val kefuid = if (MyUtils.isLogin()) MyUtils.getUserid() else "小肚驴游客"
//                val userSig = GenerateTestUserSig.genTestUserSig(kefuid)
            val userSig =  RxHttp.get("im/generateUserSig")
                .add("userId", MyUtils.getUserid())
                .toResponse<Any>().await()


            TUIKit.login(kefuid, userSig as String?, object : IUIKitCallBack {
                override fun onError(module: String, code: Int, desc: String) {
                    runOnUiThread { ToastUtil.toastLongMessage(getString(R.string.failed_login_tip) + ", errCode = " + code + ", errInfo = " + desc) }
                    DemoLog.i("ssssssssss", "imLogin errorCode = $code, errorInfo = $desc")
                    SPUtils.getInstance().remove("token")
                    SPUtils.getInstance().remove("personinfo")
                    goMain();
                }

                override fun onSuccess(data: Any?) {
                    UserInfo.getInstance().setAutoLogin(true)
                    LogUtils.e("登录成功")
                    goMain();
                }
            })
        }

    }

    private fun goMain() {
        GlobalScope.launch(Dispatchers.Main) {
            delay(DELAY_TIME)
            Router.newIntent(this@FirstActivity).to(MainActivity::class.java).launch()
//                Router.newIntent(this@FirstActivity).to(SettingActivity::class.java).launch()
            finish()
        }
    }

}